import time
time1 = time.time()
from math import sqrt

def is_prime(n):
    for i in range(2,round(sqrt(n))+1):
        if n%i==0:
            return False
    return True


def they_can_reverse(comb):
    '''两个数前后相接后是否为质数'''
    if is_prime(comb[0]*(10**len(str(comb[1]))) + comb[1]) and is_prime(comb[1]*(10**len(str(comb[0]))) + comb[0]):
        return True
    else:
        return False

step = 1000
st = 3

can_reverse = dict()

primes = []
has_cal = []

secdict = {}
thirddict = {}
fourthdict = {}
fifthdict = {}

while True:
    for end_step in range(st,st+step,2):
        if is_prime(end_step):
            primes.append(end_step)
    st = st + step
    print(st)
    if 5 in primes:
        primes.remove(5)

    for prime in primes:
        can_reverse.setdefault(prime,[])
        for key in can_reverse.keys():
            if key < prime and they_can_reverse((key,prime)):
                lis = can_reverse.get(key)
                lis.append(prime)

    while_break = False

    for key,value in can_reverse.items():
        for prime in value:
            prime_value = can_reverse.get(prime)
            tmp = [i for i in value if i in prime_value]
            if tmp:
                v = [key,prime]
                v.sort()
                v = tuple(v)
                secdict[v]=tmp

    for key,value in secdict.items():
        for prime in value:
            prime_value = can_reverse.get(prime)
            tmp = [i for i in value if i in prime_value]
            if tmp:
                v = list(key)
                v.append(prime)
                v.sort()
                v = tuple(v)
                thirddict[v]=tmp

    for key,value in thirddict.items():
        for prime in value:
            prime_value = can_reverse.get(prime)
            tmp = [i for i in value if i in prime_value]
            if tmp:
                v = list(key)
                v.append(prime)
                v.sort()
                v = tuple(v)
                fourthdict[v]=tmp

    for key,value in fourthdict.items():
        for prime in value:
            prime_value = can_reverse.get(prime)
            tmp = [i for i in value if i in prime_value]
            if tmp:
                v = list(key)
                v.append(prime)
                v.sort()
                v = tuple(v)
                print(v)
                print(tmp)
                fifthdict[v]=tmp
                while_break = True

    if while_break:
        break

print(time.time()-time1)